<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getBookListAPI,
  deleteBookAPI,
  getBookDetailsAPI,
  addBookAPI,
  updateBookAPI,
} from "@/api/manageBook";
import BookDialog from "@/components/BookDialog.vue";
import DeleteConfirm from "@/components/DeleteConfirm.vue";

const loading = ref(false);
const bookList = ref([]);
const total = ref(0);
const bookDialog = ref(null);
const currentBook = ref({});
const dialogMode = ref("add");

const deleteConfirm = ref(null)  // 删除确认框

// 分页参数
const pagination = ref({
  pagenum: 1,
  pagesize: 10,
});

// 筛选参数
const filterParams = ref({
  type: "",
  bookName: "",
  number: "",
});

// 获取图书列表
const fetchBookList = async () => {
  try {
    loading.value = true;
    const params = {
      ...pagination.value,
      ...filterParams.value,
    };

    const response = await getBookListAPI(params);

    if (response.data.code === 1) {
      bookList.value = response.data.data;
      total.value = response.data.total;
    } else {
      ElMessage.error("获取图书列表失败: " + response.data.msg);
    }
  } catch (error) {
    ElMessage.error("获取图书列表出错: " + error.message);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.value.pagenum = 1;
  console.log(filterParams.value);

  fetchBookList();
};

// 重置筛选
const resetFilter = () => {
  filterParams.value = {
    type: "",
    bookName: "",
    number: "",
  };
  handleSearch();
};

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.value.pagesize = val;
  fetchBookList();
};

// 当前页码变化
const handleCurrentChange = (val) => {
  pagination.value.pagenum = val;
  fetchBookList();
};

// 添加图书
const handleAddBook = () => {
  dialogMode.value = "add";
  currentBook.value = {};
  bookDialog.value.openDialog();
};

// 编辑图书
const handleEdit = async (row) => {
  try {
    loading.value = true;
    const res = await getBookDetailsAPI(row.id);
    console.log(res);
    
    if (res.data.code === 1) {
      dialogMode.value = "edit";
      currentBook.value = { ...res.data.data };
      bookDialog.value.openDialog();
    } else {
      ElMessage.error(res.data.msg || "获取图书详情失败");
    }
  } catch (error) {
    ElMessage.error("获取图书详情出错: " + error.message);
  } finally {
    loading.value = false;
  }
};

//删除图书
const handleDelete = async (row) => {
  const confirmed = await deleteConfirm.value.show(`确定要删除图书《${row.bookName}》吗?`)
  if (!confirmed) {
    ElMessage.info("已取消删除")
    return
  }
  
  try {
    const res = await deleteBookAPI(row.id)
    if (res.data.code === 1) {
      ElMessage.success("删除成功")
      fetchBookList()
    } else {
      ElMessage.error(res.data.msg || "删除失败")
    }
  } catch (error) {
    ElMessage.error("删除出错: " + error.message)
  }
}

// 处理表单提交
const handleSubmit = async (formData) => {
  try {
    loading.value = true;
    if (dialogMode.value === "add") {
      await addBookAPI(formData);
      ElMessage.success("添加成功");
    } else {
      formData.append("id", currentBook.value.id);
      await updateBookAPI(formData);
      ElMessage.success("更新成功");
    }
    fetchBookList();
  } catch (error) {
    ElMessage.error(error.message || "操作失败");
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchBookList();
});
</script>

<template>
  <div class="book-manage-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>图书管理</span>
          <el-button type="primary" @click="handleAddBook">添加图书</el-button>
        </div>
      </template>

      <!-- 筛选表单 -->
      <div class="filter-form">
        <el-form :inline="true" :model="filterParams">
          <el-form-item label="图书类型">
            <el-select
              v-model="filterParams.type"
              placeholder="请选择图书类型"
              clearable
            >
              <el-option label="文学类" value="文学类" />
              <el-option label="科技类" value="科技类" />
              <el-option label="历史类" value="历史类" />
              <el-option label="艺术类" value="艺术类" />
            </el-select>
          </el-form-item>
          <el-form-item label="图书名称">
            <el-input
              v-model="filterParams.bookName"
              placeholder="请输入图书名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="图书编号">
            <el-input
              v-model="filterParams.number"
              placeholder="请输入图书编号"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 图书列表 -->
      <el-table :data="bookList" border v-loading="loading">
        <el-table-column prop="number" label="图书编号" width="120" />
        <el-table-column prop="bookName" label="图书名称" width="180" />
        <el-table-column prop="type" label="类型" width="120" />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="price" label="价格" width="100" align="center">
          <template #default="{ row }">{{ row.price }}元</template>
        </el-table-column>
        <el-table-column prop="language" label="语言" width="100" />
        <el-table-column prop="location" label="位置" width="100" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.pagenum"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pagination.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </el-card>

    <!-- 图书对话框组件 -->
    <BookDialog
      ref="bookDialog"
      :mode="dialogMode"
      :bookData="currentBook"
      @submit="handleSubmit"
    />
    <!-- 删除确认框 -->
    <DeleteConfirm ref="deleteConfirm" />
  </div>
</template>

<style scoped>
.book-manage-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
